import { defineStore } from 'pinia';
import { ref } from 'vue';
import { login, logout, getUserInfo } from '@/api/auth';

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '');
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'));
  const permissions = ref([]);

  // 初始化权限（如果有用户信息）
  if (userInfo.value && userInfo.value.role !== undefined) {
    setPermissions(userInfo.value.role);
  }

  // 设置token
  function setToken(newToken) {
    token.value = newToken;
    localStorage.setItem('token', newToken);
  }

  // 设置用户信息
  function setUserInfo(user) {
    userInfo.value = user;
    localStorage.setItem('userInfo', JSON.stringify(user));
    // 根据用户角色设置权限
    setPermissions(user.role);
  }

  // 根据角色设置权限
  function setPermissions(role) {
    // 基本菜单权限（所有用户都可访问）
    const basicPermissions = [
      'dashboard',
      'customer-analysis',
      'rfm-analysis',
      'customer-lifecycle',
      'marketing-analysis',
      'sales-prediction',
      
      // New Store Dashboard Hub and its screens
      'store-dashboard-hub',
      'operational-data',
      'distribution-data',
      'store-data',

      'sales',
      'sales:orders',
      'sales:customers',
      'sales:products',
      'sales:expirations',
      'sales:server-rental',
      
      'attendance',
      'attendance:record',
      'attendance:calendar',
      'attendance:salary',
      'attendance:detail',
      'attendance:commission'
    ];

    // 管理员特有权限
    const adminPermissions = [
      'sales:commission-categories',
      'management',
      'management:employees',
      'management:products'
    ];

    if (role === 1) {  // 1代表管理员
      permissions.value = [...new Set([...basicPermissions, ...adminPermissions])];
    } else {
      permissions.value = [...new Set(basicPermissions)];
    }
    console.log('Permissions set for role ', role, ':', permissions.value);
  }

  // 登录
  async function userLogin(username, password, rememberMe = true) {
    try {
      const res = await login(username, password, rememberMe);
      
      // 确保响应中包含token和user数据
      if (!res.token || !res.user) {
        console.error('登录响应格式错误:', res);
        throw new Error('登录失败: 服务器返回数据格式错误');
      }
      
      setToken(res.token);
      setUserInfo(res.user);
      return res;
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  }

  // 获取用户信息
  async function getUserData() {
    const res = await getUserInfo();
    setUserInfo(res.data);
    return res;
  }

  // 登出
  async function userLogout() {
    try {
      await logout();
    } finally {
      resetState();
    }
  }

  // 重置状态
  function resetState() {
    token.value = '';
    userInfo.value = {};
    permissions.value = [];
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
  }

  // 检查是否有某权限
  function hasPermission(permission) {
    // 确保permissions非空
    if (!permissions.value || permissions.value.length === 0) {
      // 重新设置权限
      if (userInfo.value && userInfo.value.role !== undefined) {
        setPermissions(userInfo.value.role);
      }
    }
    console.log('检查权限:', permission, '当前权限列表:', permissions.value);
    return permissions.value.includes(permission);
  }

  // 判断是否为管理员
  function isAdmin() {
    return userInfo.value.role === 1;
  }

  return {
    token,
    userInfo,
    permissions,
    setToken,
    setUserInfo,
    userLogin,
    getUserData,
    userLogout,
    hasPermission,
    isAdmin
  };
}); 